import axios from "axios";
import storage from "@/utils/storage";
import { ServiceBaseUrl } from "./config";
var requestingCount = 0;
var loadingTime = null;

let headers = {
  Accept: "application/json",
  "Content-Type": "application/json;charset=utf-8",
  "Access-Control-Allow-Credentials": "true"
};
const tokenHeaderName = "x-auth-token";

export function requestfilter(configuration) {
  var customerShowLoading = configuration.headers["showloading"] !== false;
  // if (storage.storage.companyid()) {
  //   headers["wx-companysysno"] = storage.storage.companyid();
  // }
  // if (storage.storage.sharecardsysno() > 0) {
  //   headers["wx-sharecardsysno"] = storage.storage.sharecardsysno();
  // }
  // if (storage.storage.usersysno()) {
  //   headers["wx-usersysno"] = storage.storage.usersysno();
  // }
  if (requestingCount === 0 && customerShowLoading) {
  }
  requestingCount++;
  let h = {};
  //let token = storage.storage.token();
  h[tokenHeaderName] = 123;
  configuration.withCredentials = true;
  configuration.headers = Object.assign(
    {},
    headers,
    h,
    configuration.headers || {}
  );
  return configuration;
}
export function responsefilter(response) {
  // 如果服务器端更新了token,则保存token
  if (response.headers) {
    let newToken = response.headers[tokenHeaderName];
    // if (newToken != null) {
    //   storage.storage.token(newToken);
    // }
    requestingCount--;
    if (requestingCount === 0) {
      if (loadingTime) {
        clearTimeout(loadingTime);
        loadingTime = null;
      }
    }
  }
  return response.data;
}

class _serviceClient {
  service = null;
  setRequestInterceptors(requestInterceptor) {
    // request interceptor
    this.service.interceptors.request.use(
      request => {
        if (requestInterceptor) {
          requestInterceptor(request);
        }
        return request;
      },
      error => {
        console.log(error);
        Promise.reject(error);
      }
    );
  }
  setResponseInterceptors(responseInterceptor) {
    this.service.interceptors.response.use(
      response => {
        // 如果是文件直接返回 响应流
        // if (response.config.responseType == 'blob') {
        //   return response
        // }
        const res = response.data;
        // if (res.Success == false) {
        //   Message({
        //     message: res.Message,
        //     type: 'error',
        //     duration: 3 * 1000
        //   })
        // }
        if (responseInterceptor) {
          responseInterceptor(response);
        }
        return res;
      },
      error => {
        let response = {
          Success: false,
          Message: "网络加载失败,请更换其它网络重试!",
          Data: null
        };
        let data = {
          data: response
        };
        requestingCount--;
        if (requestingCount === 0) {
          if (loadingTime) {
            clearTimeout(loadingTime);
            loadingTime = null;
          }
        }
        console.log(error);
        return response;
      }
    );
  }
  iniService(baseURL, requestInterceptor, responseInterceptor) {
    // create an axios instance
    // this.service = axios.create({
    //   baseURL: baseURL, // process.env.UPLOAD_FILE_SERVER, // api 的 base_url
    //   timeout: 20000, // request timeout
    //   withCredentials: true
    // })
    axios.defaults.baseURL = ServiceBaseUrl;
    axios.defaults.timeout = 10000;
    axios.defaults.withCredentials = true;
    this.service = axios.create(axios.defaults);
    this.setRequestInterceptors(requestInterceptor);
    this.setResponseInterceptors(responseInterceptor);
  }
  getResultPromise(result) {
    const p = new Promise(function(resolve, reject) {
      if (result.Success !== true) {
        result.message = result.Message;
        reject(result);
        return;
      }
      resolve(result);
    });
    return p;
  }
  request(config) {
    return this.service.request(config).then(r => {
      // 如果是文件直接返回 响应流
      if (config.responseType === "blob") {
        return r;
      }
      return this.getResultPromise(r);
    });
  }
  post(url, data, config) {
    return this.service.post(url, data, config).then(r => {
      return this.getResultPromise(r);
    });
  }
  get(url, config) {
    return this.service.get(url, config).then(r => {
      return this.getResultPromise(r);
    });
  }
  delete(url, config) {
    return this.service.delete(url, config).then(r => {
      return this.getResultPromise(r);
    });
  }
  head(url, config) {
    return this.service.head(url, config).then(r => {
      return this.getResultPromise(r);
    });
  }
  put(url, data, config) {
    return this.service.put(url, data, config).then(r => {
      return this.getResultPromise(r);
    });
  }
  patch(url, data, config) {
    return this.service.patch(url, data, config).then(r => {
      return this.getResultPromise(r);
    });
  }
}
const ServiceClient = new _serviceClient();
ServiceClient.iniService(null, requestfilter, responsefilter);

export default ServiceClient;
